<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
      @input="keyword(value)"
      background="#3296fa"
    />
    <!-- 历史搜索区域 -->
    <div v-if="value.length == 0 && historyList !== []">
      <van-cell title="历史区域">
        <template #right-icon>
          <van-icon
            name="delete-o"
            color="rgba(168, 69, 69, 0.849)"
            @click="delAll"
          />
        </template>
      </van-cell>
      <van-cell
        :title="item"
        icon="search"
        v-for="(item, index) in historyList"
        :key="index"
        @click="toSearch(item)"
      >
        <template #right-icon>
          <span @click.stop="delHistory(index)">
            <van-icon color="rgba(168, 69, 69, 0.849)" name="cross"
          /></span>
        </template>
      </van-cell>
    </div>
    <!-- 联想区域 -->
    <div v-else>
      <van-cell title="联想区域" />
      <van-cell
        icon="search"
        v-for="(item, index) in suggestionList"
        :key="index"
        @click="suggestionSearch(item)"
      >
        <template #title>
          <div v-html="item.newItem"></div>
        </template>
      </van-cell>
    </div>
  </div>
</template>

<script>
import { localSet, localGet, localDel } from '@/utils/mylocal'
import { getLeve } from '@/api/search'
import { Toast } from 'vant'
export default {
  data () {
    return {
      value: '',
      lastTime: 0,
      historyList: [], // 历史搜索列表
      suggestionList: [] // 联想词
    }
  },
  methods: {
    // 删除全部历史记录
    delAll () {
      // 弹出提示框
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否删除全部历史记录'
        })
        .then(() => {
          localDel('historyValue')
          this.historyList = []
        })
        .catch(() => {
          // on cancel
        })
    },
    // 点击删除单个历史记录
    delHistory (index) {
      localDel('historyValue', this.historyList.splice(index, 1))
      localSet('historyValue', this.historyList)
      Toast.success('删除成功')
    },
    // 回车搜索
    onSearch (val) {
      if (this.value.trim() === '') {
        this.value = ''
        return
      }
      this.value = val.trim()
      // 跳转
      this.toSearch(val)
      this.value = ''
    },
    // 点击历史记录跳转到搜索结果
    toSearch (item) {
      this.historyList.unshift(item)
      // 去重
      this.historyList = [...new Set(this.historyList)]
      // 储存历史搜索数据
      localSet('historyValue', this.historyList)
      //  console.log('去重', this.historyList)
      this.$router.push(`/searchResult/:${item}`)
      Toast.success('加载成功')
    },
    // 点击联想词语跳转到搜索结果
    suggestionSearch (item) {
      console.log(this.historyList)
      //  console.log(item)
      this.historyList.unshift(item.oldItem)
      localSet('historyValue', this.historyList)
      this.$router.push(`/searchResult/:${item.oldItem}`)
      console.log(item.oldItem)
      console.log('----')
      console.log(item)
      Toast.success('加载成功')
    },
    // 延时input事件请求
    keyword (val) {
      if (this.lastTime === 0) {
        this.lastTime = setTimeout(() => {
          this.changeVal(val)
        }, 300)
      } else {
        clearTimeout(this.lastTime)
        this.lastTime = setTimeout(() => {
          this.changeVal(val)
        }, 300)
      }
    },
    // 搜索框input事件
    async changeVal (newVal) {
      const res = await getLeve({
        q: this.value
      })
      // console.log('请求联想传入', newVal)
      // 给返回的数值重新过滤,添加高亮
      this.suggestionList = res.data.options.map(item => {
        return {
          newItem: item.replace(
            newVal,
            `<span style="color:red">${newVal}</span>`
          ),
          oldItem: item
        }
      })
      console.log(this.suggestionList)
    },
    // 取消按钮
    onCancel () {
      Toast.success('取消成功')
    }
  },
  created () {
    // 得到历史搜索列表
    this.historyList = localGet('historyValue') || []
  }
}
</script>

<style lang="less" scoped>
.search {
  /deep/ .van-search__action {
    color: #fff;
  }
  /deep/.van-cell {
    span .van-icon::before {
      display: block;
    }
  }
  /deep/.van-search__action:active{
    background-color: rgba(0, 153, 255, 0.027);
  }
}
</style>
